{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d264b685-ed95-4602-9497-4bd2123212b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "\n",
    "# 国内代理方式，或其它大模型\n",
    "chat_model = ChatOpenAI(\n",
    "    api_key = \"sk-y7DHfp9fzuCxOVm2158638099f9541D3833aB4F4Ed674aCf\",\n",
    "    base_url = \"https://vip.apiyi.com/v1\",    # 此处代理方式，如果是OpenAI官方接口需调整接口地址\n",
    "    model = \"gpt-4o-mini\",\n",
    "    max_tokens = 1000,\n",
    "    temperature = 0\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e0fa7b22-591c-4f20-a030-5bec69d00d38",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import tool\n",
    "\n",
    "@tool\n",
    "def get_word_length(word: str) -> int:\n",
    "    \"\"\"Returns the length of a word.\"\"\"\n",
    "    return len(word)\n",
    "\n",
    "tools = [get_word_length]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2bc5bf09-841e-4a6c-87c2-a42c9c71b6ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.schema import SystemMessage\n",
    "from langchain.agents import OpenAIFunctionsAgent\n",
    "from langchain.agents import AgentExecutor\n",
    "\n",
    "system_message = SystemMessage(content=\"你是非常强大的AI助手，但在计算单词长度方面不擅长。\")\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(system_message = system_message)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e86e9e7b-b3a5-4276-8be7-d191ecc28072",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Eason\\AppData\\Local\\Temp\\ipykernel_235680\\1839730416.py:1: LangChainDeprecationWarning: The class `OpenAIFunctionsAgent` was deprecated in LangChain 0.1.0 and will be removed in 1.0. Use :meth:`~create_openai_functions_agent` instead.\n",
      "  agent = OpenAIFunctionsAgent(llm=chat_model, tools=tools, prompt=prompt)\n"
     ]
    }
   ],
   "source": [
    "agent = OpenAIFunctionsAgent(llm=chat_model, tools=tools, prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d0e3bb38-8bbf-47e7-9c02-ee1ecad0b8d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "470fbb0c-1951-4483-8130-0a4b704c615b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `get_word_length` with `{'word': 'educa'}`\n",
      "\n",
      "\n",
      "\u001b[32;1m\u001b[1;3m单词“educa”中有5个字母。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '单词“educa”中有多少个字母?', 'output': '单词“educa”中有5个字母。'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke(\"单词“educa”中有多少个字母?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b4b479c-6a65-46d3-87fe-7b4b35920ed9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "b0cc621e-e1e5-4458-927d-d648081b7010",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import MessagesPlaceholder\n",
    "\n",
    "MEMORY_KEY = \"chat_history\"\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(\n",
    "    system_message=system_message,\n",
    "    extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fa062d08-fc4d-4e46-836c-d912e174b486",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Eason\\AppData\\Local\\Temp\\ipykernel_235680\\3261263376.py:2: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/\n",
      "  memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `get_word_length` with `{'word': 'educa'}`\n",
      "\n",
      "\n",
      "\u001b[32;1m\u001b[1;3m单词“educa”中有5个字母。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '单词“educa”中有多少个字母?',\n",
       " 'chat_history': [HumanMessage(content='单词“educa”中有多少个字母?', additional_kwargs={}, response_metadata={}),\n",
       "  AIMessage(content='单词“educa”中有5个字母。', additional_kwargs={}, response_metadata={})],\n",
       " 'output': '单词“educa”中有5个字母。'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)\n",
    "\n",
    "agent = OpenAIFunctionsAgent(llm=chat_model, tools=tools, prompt=prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)\n",
    "agent_executor.invoke(\"单词“educa”中有多少个字母?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c63c5264-58ba-4637-a605-ecfcf785c477",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m“educa”并不是一个常见的英语单词。它可能是“educate”的一部分或某个特定名称的缩写，但在标准英语词汇中并不存在。如果你有其他单词需要确认或查询，请告诉我！\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '那是一个真实的单词吗？',\n",
       " 'chat_history': [HumanMessage(content='单词“educa”中有多少个字母?', additional_kwargs={}, response_metadata={}),\n",
       "  AIMessage(content='单词“educa”中有5个字母。', additional_kwargs={}, response_metadata={}),\n",
       "  HumanMessage(content='那是一个真实的单词吗？', additional_kwargs={}, response_metadata={}),\n",
       "  AIMessage(content='“educa”并不是一个常见的英语单词。它可能是“educate”的一部分或某个特定名称的缩写，但在标准英语词汇中并不存在。如果你有其他单词需要确认或查询，请告诉我！', additional_kwargs={}, response_metadata={})],\n",
       " 'output': '“educa”并不是一个常见的英语单词。它可能是“educate”的一部分或某个特定名称的缩写，但在标准英语词汇中并不存在。如果你有其他单词需要确认或查询，请告诉我！'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke(\"那是一个真实的单词吗？\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2646114-2090-4c84-b1c7-b5b9db097626",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07906364-33b5-4dee-b52a-e6b5462bf94f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "447a3d2a-b2d1-48d1-8638-4a0117d5fa67",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"SERPAPI_API_KEY\"] = \"48e0c6e71b026c7711c40b3920a560957f53850b4e09f4290ab26592ad4a6a4d\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "67197a01-9ce1-4435-9eac-608d4118037c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting numexpr\n",
      "  Downloading numexpr-2.10.2-cp311-cp311-win_amd64.whl.metadata (8.3 kB)\n",
      "Requirement already satisfied: numpy>=1.23.0 in d:\\java\\miniconda3\\envs\\langchain\\lib\\site-packages (from numexpr) (1.26.4)\n",
      "Downloading numexpr-2.10.2-cp311-cp311-win_amd64.whl (144 kB)\n",
      "Installing collected packages: numexpr\n",
      "Successfully installed numexpr-2.10.2\n"
     ]
    }
   ],
   "source": [
    "!pip install numexpr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9db052e9-9f68-4bc2-91a0-4dbc9f8b48d7",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Eason\\AppData\\Local\\Temp\\ipykernel_235680\\1798154677.py:9: LangChainDeprecationWarning: LangChain agents will continue to be supported, but it is recommended for new use cases to be built with LangGraph. LangGraph offers a more flexible and full-featured framework for building agents, including support for tool-calling, persistence of state, and human-in-the-loop workflows. For details, refer to the `LangGraph documentation <https://langchain-ai.github.io/langgraph/>`_ as well as guides for `Migrating from AgentExecutor <https://python.langchain.com/docs/how_to/migrate_agent/>`_ and LangGraph's `Pre-built ReAct agent <https://langchain-ai.github.io/langgraph/how-tos/create-react-agent/>`_.\n",
      "  agent = initialize_agent(tools, chat_model, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m我需要先查找莱昂纳多·迪卡普里奥目前的女朋友是谁，然后再计算她的年龄的0.43次方。  \n",
      "Action: Search  \n",
      "Action Input: \"莱昂纳多·迪卡普里奥 现任女朋友 2023\"  \u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m李奧納多最近交往的女友是26歲超模女友維多莉亞伽里蒂（Vittoria Ceretti），兩人交往已經兩年，不僅已經超過李奧納多的「交往年限」，感情還是甜蜜蜜。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m我现在知道莱昂纳多·迪卡普里奥的女朋友是维多莉亚·伽里蒂（Vittoria Ceretti），她26岁。接下来，我需要计算她年龄的0.43次方。  \n",
      "Action: Calculator  \n",
      "Action Input: 26 ** 0.43  \u001b[0m\n",
      "Observation: \u001b[33;1m\u001b[1;3mAnswer: 4.059182145592686\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m我现在知道维多莉亚·伽里蒂的年龄的0.43次方是4.059182145592686。  \n",
      "Final Answer: 莱昂纳多·迪卡普里奥的女朋友是维多莉亚·伽里蒂（Vittoria Ceretti），她的年龄的0.43次方是4.059。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?',\n",
       " 'output': '莱昂纳多·迪卡普里奥的女朋友是维多莉亚·伽里蒂（Vittoria Ceretti），她的年龄的0.43次方是4.059。'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.agents import load_tools\n",
    "from langchain.agents import initialize_agent\n",
    "from langchain.agents import AgentType\n",
    "\n",
    "#加载 LangChain 内置的 Tools\n",
    "tools = load_tools([\"serpapi\", \"llm-math\"], llm=chat_model)\n",
    "\n",
    "# 实例化 ZERO_SHOT_REACT Agent\n",
    "agent = initialize_agent(tools, chat_model, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)\n",
    "\n",
    "agent.invoke(\"谁是莱昂纳多·迪卡普里奥的女朋友？她现在年龄的0.43次方是多少?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c215002-cb91-41b5-984f-cd894a519958",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "62083e59-5d2f-4dae-8aed-cc5249d90e3e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.utilities import SerpAPIWrapper\n",
    "from langchain.agents import initialize_agent, AgentType, Tool\n",
    "\n",
    "# 实例化查询工具\n",
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"Intermediate Answer\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to ask with search\",\n",
    "    )\n",
    "]\n",
    "self_ask_with_search = initialize_agent(\n",
    "    tools, chat_model, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True, handle_parsing_errors=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f17bc6f5-feac-4206-8a9f-2a8281b08c41",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYes.  \n",
      "Follow up: 成都举办的大运会是第几届大运会？  \u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2021年夏季世界大学生运动会（英语：2021 Summer World University Games）简称为2021年成都大运会或成都大运会，是第31届夏季世界大学生运动会，原定于2021年于中国四川省成都市举行，后因2019冠状病毒病疫情等原因二次延期，最终改至2023年7月28日至8月8日举行.\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: 第31届大运会，2023年大运会举办地是成都。\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '成都举办的大运会是第几届大运会？2023年大运会举办地在哪里？',\n",
       " 'output': '第31届大运会，2023年大运会举办地是成都。'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 实际运行 Agent，查询问题（正确）\n",
    "self_ask_with_search.invoke(\n",
    "    \"成都举办的大运会是第几届大运会？2023年大运会举办地在哪里？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "967f2e10-39ca-4d4f-8861-eb228138990a",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m是的。  \n",
      "Follow up: 2023年大运会的举办地是哪里？  \u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2018年3月5日正式宣布普莱西德湖村成为2023年冬季大运会的主办城市，国际大体联官员称这是大运会申办历史上最强有力的一次。 由于2021年冬季世界大学生运动会因2019冠状病毒病疫情而取消，将大运会会旗正式移交给普莱西德湖村的仪式改在2022年1月于都灵举行。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mFollow up: 2023年大运会是第几届大运会？  \u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3m2023年夏季世界大学生运动会（英语：XXXII 2023 Summer World University Games）简称为叶卡捷琳堡大运会，是第32届夏季世界大学生运动会。\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: 最终答案是：第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3mCould not parse output: The final answer is: 第32届大运会。\n",
      "For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE \u001b[0m\n",
      "Intermediate answer: Invalid or incomplete response\n",
      "\u001b[32;1m\u001b[1;3m\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': '2023年大运会举办地在哪里？成都举办的大运会是第几届大运会？',\n",
       " 'output': 'Agent stopped due to iteration limit or time limit.'}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search.invoke(\n",
    "    \"2023年大运会举办地在哪里？成都举办的大运会是第几届大运会？\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "bc278ad8-7ab8-46ca-9a54-b84b55c64019",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='成都举办的世界大学生夏季运动会是第31届大运会。该届大运会原定于2021年举行，但因疫情推迟至2022年。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 40, 'prompt_tokens': 20, 'total_tokens': 60, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_0392822090', 'id': 'chatcmpl-BZIRflxBNdInXXAqsHIg5witTIRRh', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None} id='run--78555b1c-0486-4038-b20d-aa23d731d550-0' usage_metadata={'input_tokens': 20, 'output_tokens': 40, 'total_tokens': 60, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n"
     ]
    }
   ],
   "source": [
    "print(chat_model.invoke(\"成都举办的大运会是第几届大运会？\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f68096d-2543-4c95-88be-8cf2504413dc",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1402d4d-b897-4415-b53b-3029e39d099e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "aaab794b-3654-4b7a-a0a1-7bcf28b6bd7f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2025-05-19 00:00:00\n"
     ]
    }
   ],
   "source": [
    "from datetime import datetime,timedelta,date\n",
    "date_start=datetime.strptime('2025-05-26', \"%Y-%m-%d\")-timedelta(days=7)\n",
    "print(date_start)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "bc3c002b-7cbe-474a-8834-6b4e48cb0201",
   "metadata": {},
   "outputs": [],
   "source": [
    "while True:\n",
    "    if date_start.weekday()!=4:\n",
    "        date_start-=timedelta(days=1)\n",
    "    else:\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "bedce589-acb3-424b-9e0b-529b3dba966d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2025-05-16 00:00:00\n"
     ]
    }
   ],
   "source": [
    "print(date_start)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "46e76a61-255e-4f3a-b3ff-3ea42c6d6eac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "592275d2-e6ea-4f2b-8f64-1a4ad40e99a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "本周开始时间：2025-05-23 00:00:00，本周结束时间：2025-05-29 00:00:00\n"
     ]
    }
   ],
   "source": [
    "date_obj = datetime.strptime('2025-05-30', \"%Y-%m-%d\")\n",
    "date_start = date_obj - timedelta(days=(date_obj.weekday() - 4) % 7 + 7)\n",
    "date_end = date_start + timedelta(days=6)\n",
    "print(f\"本周开始时间：{date_start}，本周结束时间：{date_end}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae6ed10d-6973-4bb9-acc7-c0f9ab74a769",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
